// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
// 云函数入口函数
exports.main = async(event, context) => {
  const wxContext = cloud.getWXContext()

  let db = cloud.database();
  let today = new Date()
  let sundayTimeStamp = today - today.getDay() * 24 * 3600 * 1000
  let sundayString = new Date(sundayTimeStamp).toLocaleDateString().replace(/\//g, '-')
  let res;
  const _ = db.command
  try {
    let r = await db.collection("tb_schedule").where({
        date: _.gt(sundayString),
        _openid: wxContext.OPENID
      })
      .orderBy('date', 'asc')
      .get()
    res = {}
    let list = r.data;
    let courses = ["maths", "chinese", "english", "physical", "chemistry", "history", "politics"]

    list.forEach(t => {
      if (!t.self) {
        return 0;
      }
      res[t.date] = courses.reduce((p, c) => {
        let duration = t.self[c] && t.self[c].duration || 0
        return p + duration
      }, 0)

    })
  } catch (e) {}
  return res;
}